import { ElMessage } from 'element-plus'
import { ref } from 'vue'

export const usePageFetchHook = (fetchFn, options = {}) => {
  const page = ref(1)
  const size = ref(10)
  const total = ref(0)
  const dataList = ref([])
  const searchParams = options.searchParams || {}
  page.value = options.page || 1
  size.value = options.size || 10

  const modalVisible = ref(false)
  const modalType = ref('add')
  const selectedRow = ref(null)

  const deleteModelVisible = ref(false)
  const deleteDataList = ref([])
  const deleteType = ref('single')

  const immediate = options.immediate || true

  const fetchData = async() => {
    const { data } = await fetchFn({
      ...searchParams,
      page: page.value,
      size: size.value
    })
    dataList.value = data.list
    total.value = data.total
  }

  if(immediate && fetchFn) {
    fetchData()
  }

  const handleSearch = () => {
    fetchData()
  }

  const handleChange = (pageInfo) => {
    page.value = pageInfo.page
    size.value = pageInfo.size
    fetchData()
  }
  const handleSelect = (val) => {
    deleteDataList.value = val
  }
  const handleAdd = () => {
    modalType.value = 'add'
    modalVisible.value = true
  }
  const handleEdit = (row) => {
    modalType.value = 'edit'
    modalVisible.value = true
    selectedRow.value = row
  }
  const handleDelete = (row) => {
    deleteType.value = 'single'
    deleteModelVisible.value = true
    selectedRow.value = row
  }
  const handleDetail = (row) => {
    modalType.value = 'detail'
    modalVisible.value = true
    selectedRow.value = row
  }
  const handleClose = () => {
    modalVisible.value = false
    selectedRow.value = null
  }
  const handleBatchDelete = () => {
    if(deleteDataList.value.length === 0) {
      return ElMessage.warning('请选择要删除的数据')
    }
    deleteType.value = 'batch'
    deleteModelVisible.value = true
  }

  return {
    total,
    dataList,
    page,
    size,
    modalVisible,
    modalType,
    selectedRow,
    deleteDataList,
    deleteType,
    deleteModelVisible,
    fetchData,
    handleSearch,
    handleChange,
    handleSelect,
    handleAdd,
    handleEdit,
    handleDelete,
    handleDetail,
    handleClose,
    handleBatchDelete
  }
}
